﻿
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using Kokomo.Environment;

namespace Kokomo.PeInspector
{
	[ViewType(typeof(DelayLoadView))]
	public class DelayLoadViewModel : NotifierObject
	{
		public DelayLoadViewModel(
			Func<ProgressInfo, object> contentDelegate
			)
		{
			if (contentDelegate == null) throw new ArgumentNullException("contentDelegate");

			this.LoadProgress = new ProgressInfo();
			this._contentDelegate = contentDelegate;
		}

		private bool _isLoading;
		public bool IsLoading
		{
			get { return this._isLoading; }
			set
			{
				this._isLoading = value;
				this.OnPropertyChanged("IsLoading");
			}
		}

		public ProgressInfo LoadProgress { get; private set; }

		private Func<ProgressInfo, object> _contentDelegate;

		private bool _isLoaded;
		private object _content;
		public object Content
		{
			get
			{
				lock (this)
				{
					if (
						!this._isLoaded
						&& !this._isLoading)
					{
						this.BeginLoadContent();
					}
				}

				return this._content;
			}
		}

		private void BeginLoadContent()
		{
			this.IsLoading = true;
			new Thread(this.LoadContentAsync) { Name = "DelayLoadViewModel.LoadContent" }.Start();
		}

		private void LoadContentAsync()
		{
			object content = this._contentDelegate(this.LoadProgress);
			this._content = content;
			this.OnPropertyChanged("Content");
			this.IsLoading = false;
			this._isLoaded = true;
		}
	}
}
